<template>
  <el-card>
    <el-form
      label-width="120px"
      :model="skuInfo"
      :rules="skuFormRules"
      ref="skuFormRef"
    >
      <el-form-item label="SPU名称">
        <span>{{ currentSpuInfo.spuName }}</span>
      </el-form-item>
      <el-form-item label="SKU名称" prop="skuName">
        <el-input :v-model="skuInfo.skuName" placeholder="SKU名称"></el-input>
      </el-form-item>
      <el-form-item label="价格(元)" prop="price">
        <el-input
          :v-model="skuInfo.price"
          type="number"
          :min="0"
          :max="100"
        ></el-input>
      </el-form-item>
      <el-form-item label="重量(千克)" prop="weight">
        <el-input
          v-model="skuInfo.weight"
          type="number"
          :min="0"
          :max="100"
        ></el-input>
      </el-form-item>
      <el-form-item label="规格描述" prop="skuDesc">
        <el-input
          :v-model="skuInfo.skuDesc"
          type="textarea"
          placeholder="请输入sku描述"
          rows="4"
        ></el-input>
      </el-form-item>

      <el-form-item label="平台属性" prop="skuAttrValueList">
        <el-row :gutter="10">
          <el-col
            v-for="(attr, index) in attrList"
            :key="attr.id"
            :xs="24"
            :sm="12"
            :md="8"
            :lg="8"
            :xl="6"
          >
            <el-form-item style="margin-bottom: 10px" :label="attr.attrName">
              <el-select
                v-model="skuInfo.skuAttrValueList[index]"
                placeholder="请选择"
                @change="toClearAttrValueRules"
              >
                <el-option
                  v-for="attrValue in attr.attrValueList"
                  :key="attrValue.id"
                  :label="attrValue.valueName"
                  :value="`${attr.id}:${attr.attrName}:${attrValue.id}:${attrValue.valueName}`"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item label="销售属性" prop="skuSaleAtteValueList">
        <el-row :gutter="10">
          <el-col
            v-for="(saleAttr, index) in spuSaleAttrList"
            :key="saleAttr.id"
            :xs="24"
            :sm="12"
            :md="12"
            :lg="8"
            :xl="8"
          >
            <el-form-item :label="saleAttr.saleAttrName">
              <el-select
                v-model="skuInfo.skuSaleAttrValueList[index]"
                @change="toClearSaleAttrRules"
                placeholder="请选择"
              >
                <el-option
                  v-for="saleAttrValue in saleAttr.spuSaleAttrValueList"
                  :label="saleAttrValue.saleAttrValueName"
                  :value="`${saleAttr.id}:${saleAttr.saleAttrName}:${saleAttrValue.id}:${saleAttrValue.saleAttrValueName}`"
                  :key="saleAttrValue.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="图片列表" prop="skuImageList">
        <el-table
          border
          :data="spuImageList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            type="selection"
            align="center"
            width="80"
          ></el-table-column>
          <el-table-column label="图片">
            <template v-slot="{ row }">
              <el-image
                style="width: 100px; height: 100px"
                :src="row.imgUrl"
                fit="fill"
              />
            </template>
          </el-table-column>
          <el-table-column label="名称" prop="imgName"></el-table-column>
          <el-table-column label="操作">
            <template v-slot="{ row }">
              <el-button
                type="primary"
                v-if="row.isDefault === '0'"
                @click="toSetDefaultImg(row)"
                >设置默认图片</el-button
              >
              <el-button type="success" v-else disabled>默认图片</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-button
        type="primary"
        style="margin-left: 120px"
        @click="submitSkuForm(skuFormRef)"
        >保存</el-button
      >
      <el-button>取消</el-button>
    </el-form>
  </el-card>
</template>

<script lang="ts">
export default {
  name: 'SkuForm',
};
</script>

<script lang="ts" setup>
import { onMounted, ref, reactive } from 'vue';
import {
  reqGetSpuImageListData,
  reqGetSpuSaleAttrListData,
} from '@/api/product/spu';
import { reqGetAttrListData } from '@/api/product/attr';
import { reqSaveSkuInfo } from '@/api/product/sku';
import { useCategoryListStore } from '@/stores/categoryList';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import { ShowStatus } from '../types';

const props = defineProps(['currentSpuInfo']);
const emits = defineEmits(['setShowStatus']);
const categoryStore = useCategoryListStore();
const spuImageList = ref([]);
const spuSaleAttrList = ref([]);
const attrList = ref([]);
const skuFormRef = ref<FormInstance>();

const skuInfo = reactive({
  skuName: '', // sku名称
  spuId: -1, // spu的id
  tmId: 0, //品牌id
  weight: 1, // 重量
  skuDefaultImg: '', // 设置的默认图片链接
  skuDesc: '', // sku描述
  category3Id: 0, // 分类的3Id
  price: 1, // 价格
  // 平台属性
  skuAttrValueList: [],
  // 图片列表
  skuImageList: [],
  // 销售属性数组
  skuSaleAttrValueList: [],
});

//自定义校验规则
const skuAttrValueListRule = (rule: any, value: any, callback: any) => {
  if (!value.length) {
    callback('平台属性至少要选择一个.'); // 里面的参数表示提示内容
    return;
  }

  // 下面这样写表示通过了校验规则
  callback();
};

const skuSaleAttrValueListRule = (rule: any, value: any, callback: any) => {
  if (!value.length) {
    return callback('请至少选择一个销售属性.');
  }

  callback();
};

// 验证图片
const skuImageListRule = (rule: any, value: any, callback: any) => {
  if (value.length < 3) {
    return callback('请至少选择三张图片.');
  }

  callback();
};

// 书写校验规则
const skuFormRules = reactive<FormRules>({
  skuName: [
    { required: true, message: '请填写Sku名称', trigger: 'blur' },
    { min: 2, max: 10, message: '长度应该在2--10之间', trigger: 'blur' },
  ],
  price: [
    {
      required: true,
      message: '请设置一个价格',
      trigger: 'change',
    },
  ],
  weight: [
    {
      required: true,
      message: '请添加一个重量',
      trigger: 'change',
    },
  ],
  skuDesc: [{ required: true, message: '请输入Sku描述', trigger: 'blur' }],
  skuImageList: [
    { required: true, validator: skuImageListRule, trigger: 'change' },
  ],
  skuAttrValueList: [
    { required: true, validator: skuAttrValueListRule, trigger: 'change' },
  ],
  skuSaleAttrValueList: [
    { required: true, validator: skuSaleAttrValueListRule, trigger: 'change' },
  ],
});

// 1. 页面挂载完毕 去请求三种数据
onMounted(async () => {
  try {
    const { id: spuId } = props.currentSpuInfo;
    const { category1Id, category2Id, category3Id } = categoryStore;
    const [resSpuImageList, resSpuSaleAttrList, resAttrList] =
      await Promise.allSettled([
        reqGetSpuImageListData(spuId),
        reqGetSpuSaleAttrListData(spuId),
        reqGetAttrListData({ category1Id, category2Id, category3Id }),
      ]);

    // 判断是否请求成功
    if (resSpuImageList.status === 'fulfilled') {
      spuImageList.value = resSpuImageList.value.map((item) => {
        return {
          ...item,
          isDefault: '0', // 额外再添加一个属性 用来设置是否是默认项
        };
      });
    }
    if (resSpuSaleAttrList.status === 'fulfilled') {
      spuSaleAttrList.value = resSpuSaleAttrList.value;
    }
    if (resAttrList.status === 'fulfilled') {
      attrList.value = resAttrList.value;
    }
  } catch (error) {
    console.log('error', error);
  }
});

// 2. 设置默认图片
const toSetDefaultImg = (row) => {
  // 先将其它的设置为0
  spuImageList.value.forEach((item) => {
    item.isDefault = '0';
  });

  // 将当前自身的那一个设置为1
  row.isDefault = '1';

  // 收集一下当前默认图片的链接 保存起来
  skuInfo.skuDefaultImg = row.imgUrl;
};

// 3. 清空平台属性的校验规则
const toClearAttrValueRules = () => {
  skuFormRef.value?.clearValidate(['skuAttrValueList']);
};

// 4. 清空销售属性的校验规则
const toClearSaleAttrRules = () => {
  skuFormRef.value?.clearValidate(['skuSaleAttrValueList']);
};

// 5. 收集选中的图片
const handleSelectionChange = (val) => {
  // console.log('aav', val);
  if (val.length >= 3) {
    skuFormRef.value?.clearValidate(['skuImageList']);
  }
  // 把选中的图片收集起来
  skuInfo.skuImageList = val;
};
// 6. 添加skuInfo
const submitSkuForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      // 1 处理一下平台属性
      skuInfo.skuAttrValueList = skuInfo.skuAttrValueList
        .filter(Boolean)
        .map((item) => {
          console.log('111', item);
          const [attrId, attrName, valueId, valueName] = item.split(':');
          return {
            attrId,
            attrName,
            valueId,
            valueName,
          };
        });

      // 2 处理一下销售属性
      skuInfo.skuSaleAttrValueList = skuInfo.skuSaleAttrValueList
        .filter(Boolean)
        .map((item) => {
          const [saleAttrId, saleAttrName, saleAttrValueId, saleAttrValueName] =
            item.split(':');
          return {
            saleAttrId,
            saleAttrName,
            saleAttrValueId,
            saleAttrValueName,
          };
        });

      // 3 检测默认图片是否在选择图片当中
      if (!skuInfo.skuImageList.find((item) => item.isDefault === '1')) {
        ElMessage.warning('请在图片列表中选择一个默认图片...');
        return;
      }

      skuInfo.category3Id = categoryStore.category3Id;
      skuInfo.spuId = props.currentSpuInfo.id;
      skuInfo.tmId = props.currentSpuInfo.tmId;

      // 最终发送请求 添加skuInfo
      await reqSaveSkuInfo(skuInfo);

      // 提示用户添加成功
      ElMessage.success('添加skuInfo成功了...');
      // 跳转到spu列表页面
      emits('setShowStatus', ShowStatus.SPU_LIST);
    } else {
      console.log('error submit!');
      return false;
    }
  });
};
</script>

<style></style>
